package com.wendyxie.sproutup.view

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.wendyxie.sproutup.databinding.ActivityAddScoreTmpBinding
import com.wendyxie.sproutup.db.SQLInitHelper
import com.wendyxie.sproutup.db.SQLUserScoreTmplHelper
import com.wendyxie.sproutup.entity.UserScoreTmplEntity

class AddScoreTmplActivity : AppCompatActivity() {
    private lateinit var binding: ActivityAddScoreTmpBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityAddScoreTmpBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // TODO: 是否自动： 是-则显示radiogroup, 否-则不显示
        binding.switchAuto.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                binding.rgFrequency.visibility = android.view.View.VISIBLE
            } else {
                binding.rgFrequency.visibility = android.view.View.GONE
            }
        }

        // 按钮点击：添加
        binding.btnAdd.setOnClickListener {
            addScoreTmpl()
            finish()
        }
    }

    private fun addScoreTmpl() {
        // 检查输入
        if (binding.editTitle.text.toString().isEmpty()) {
            binding.editTitle.error = "请输入名称"
        }
        if (binding.editScore.text.toString().isEmpty()) {
            binding.editScore.error = "请输入分数"
        }
        if (binding.editScore.text.toString().isEmpty() || binding.editTitle.text.toString().isEmpty()) {
            Log.d("AddScoreTmplActivity", "addScoreTmpl: 输入为空")
            return
        }
        // TODO: 添加模板
        val scoreTmplEntity = UserScoreTmplEntity(
            score = binding.editScore.text.toString().toInt(),
            frequency = if (binding.switchAuto.isChecked) {
                when (binding.rgFrequency.checkedRadioButtonId) {
                    binding.rbFrequencyDay.id -> "DAY"
                    binding.rbFrequencyWeek.id -> "WEEK"
                    else -> ""
                }
                binding.rgFrequency.checkedRadioButtonId.toString()
            } else {
                ""
            },
            scoreTitle = binding.editTitle.text.toString(),
            isAuto = if (binding.switchAuto.isChecked) 1 else 0
        )
        Log.d("AddScoreTmplActivity", "addScoreTmpl: $scoreTmplEntity")
        // 添加到数据库
        try {
            SQLUserScoreTmplHelper.addUserScoreTmpl(scoreTmplEntity, SQLInitHelper(this).openDatabase())
        } catch (e: Exception) {
            Log.d("AddScoreTmplActivity", "addScoreTmpl error: ${e.message}")
        }

    }
}
